﻿using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace nhCommon
{
    public class NhUi
    {
        /// <summary>
        /// DataGridView中列累加
        /// </summary>
        /// <param name="dgv">DataGridView</param>
        /// <param name="columIndex">列序号</param>
        /// <returns></returns>
        public static double DGCellSumToDouble(DataGridView dgv, int columIndex)
        {
            double totalprice = 0;
            double Dtotal = 0;
            if (dgv.Rows.Count > 0)
            {
                bool isDouble = (dgv.Columns[columIndex].ValueType == typeof(double)) || (dgv.Columns[columIndex].ValueType == typeof(double?));
                bool isInt = (dgv.Columns[columIndex].ValueType == typeof(int)) || (dgv.Columns[columIndex].ValueType == typeof(int?));
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    if (dgv.Rows[i].Visible)
                    {
                        if (isDouble)
                        {
                            totalprice += NhDb.DbToValue<double>(dgv.Rows[i].Cells[columIndex].Value);
                        }
                        else if (isInt)
                        {
                            totalprice += NhDb.DbToValue<int>(dgv.Rows[i].Cells[columIndex].Value);
                        }
                    }
                }
                Dtotal = totalprice;
            }
            return Dtotal;
        }

        /// <summary>
        /// 根据内容改变TextBox长度，可放入TextChanged事件
        /// </summary>
        /// <param name="sender">TextBox控件</param>
        public static void TxtChangeWidth(object sender)
        {
            if (sender is TextBox tb)
            {
                if (tb.Text != "")
                {
                    if (tb.Width < 200 || tb.TextLength <= 16)
                    {
                        if (tb.TextLength >= 1)
                        {
                            //判断是否为汉字，关键
                            const string pattern1 = @"^[\u4e00-\u9fa5]+$";
                            Graphics g = tb.CreateGraphics();
                            System.Drawing.SizeF s = g.MeasureString(tb.Text, tb.Font);
                            if (Regex.IsMatch(tb.Text, pattern1))
                            {
                                tb.Width = (int)s.Width + 14;
                            }
                            else
                            {
                                tb.Width = (int)s.Width + 8;
                            }
                        }
                    }
                }
                else
                {
                    tb.Width = 63; //没内容时回到初始大小
                }
            }
        }
    }
}
